<template>
	<view>
		<!--  #ifdef  MP || APP-PLUS-->
		<cu-custom bgColor="bg-white" :isBack="false">
			<!-- <block slot="backText">返回</block>-->
			<block slot="content">购物车</block> 
		</cu-custom>
		<!--  #endif -->
		<div class="cart">
			<div class="cartlist">
				<div class="item" :data-index="index" v-for="(item,index) in listData" :key="index">
					<div class="category">
						<div class="icon" :class="[ Listids[index] ? 'active' : '']" @click="changeColor(index,item.categoryCode)"></div>
						{{item.categoryName}}
					</div>
					<div class="product" :data-index="index" v-for="(good,goodIndex) in item.goodsList" :key="goodIndex">
						<div class="con">
							<div class="left">
								<div class="icon" :class="[ SelectGoods[good.id] == true ? 'active' : '']" @click="changeGoodsColor(index,goodIndex,good)">
								</div>
							</div>
							<div class="right">
								<div class="ctr">
									<div class="info">
										<p style="text-align: left;">{{good.productName}}</p>
										<p style="text-align: left;margin-left: 1px;color:red;">{{parseFloat(good.price).toFixed(2)}} 元</p>
									</div>
									<view class="left" >
									
										<span style="color:red;font-weight: 600;font-size: 16px;margin-right: 2px;"  @click="myDelGoods(index,goodIndex,good)">×</span>
										
										<span @click="countGoodsNumber(index,goodIndex, good,false)" style="font-size: 25rpx;font-weight: 600;color:blue;background-color: #fffbf7;">-</span>
										<input type="number" style="width: 50px;" v-model.number="good.num" @blur="setCartValue(index, goodIndex, good, $event)" />
										<span @click="countGoodsNumber(index,goodIndex,good,true)" style="font-size: 25rpx;font-weight: 600;color: blue;background-color: #fffbf7;">+</span>
									</view>
								</div>
							</div>
						</div>
					</div>
				</div>
			</div>
			<div class="nogoods" v-if="listData.length == 0">
				<image style="width: 160px; height: 160px;display: block;margin: 0 auto;" src="../../static/images/noCart.png"></image>
				<view class="text">
					购物车空空如也~~
				</view>
			</div>
			<div class="fixed" v-if="listData.length != 0">
				<div @click="allCheck" :class="{active:allcheck}" class="left">全选({{isCheckedNumber}}) <label class="price">合计: {{parseFloat(allPrice).toFixed(2)}} 元</label></div>
				<div class="right">
					<div></div>
					<div @click="orderDown">确认订单</div>
				</div>
			</div>
		</div>
	</view>
</template>

<script>
	import {
		checkTodayOrderCountApi
	} from "@/server/config.js";

	import {
		toLogin,
		getStorageCartInfo,
		setStorageCartInfo,
		get
	} from "@/server/api.js";

	export default {
		async onShow() {
			let openId = uni.getStorageSync('openid');
			if (openId) {
				await get('/erp/openid/find', {openid:openId}).then(function(res) {
					if (!res.data.records[0]) {
						uni.navigateTo({
							url: "/apiPam/logincommon/main"
						});
					}
				})
			}
			this.getListData();
		},
		created() {},
		data() {
			return {
				allPrice: 0,
				allcheck: false,
				listData: [],
				Listids: [],
				SelectGoods: {},
				ListGoods: []
			};
		},
		components: {},
		methods: {
			// 手动输入数量触发
			async changeCartNumber(goods_id, number, product_id, goods_number) {
				let yz_number = /^\d+$/;
				goods_number = goods_number.replace(/[^\d]/g, ''); // 清除“数字”和“.”以外的字符
				if (goods_number.indexOf('.') < 0 && goods_number != '') {
					// 以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额
					goods_number = parseInt(goods_number);
				} else {
					this.getListData();
					return false;
				}

				if (number <= 0) {
					let _this = this;
					uni.showToast({
						icon: "none",
						duration: 1000,
						title: "数量不能小于等于0",
						success: function() {
							setTimeout(function() {
								_this.getListData();
							}, 1000);
						}
					});

					return false;
				}

				if (yz_number.test(number) === false) {
					uni.showToast({
						icon: "none",
						duration: 1000,
						title: "数量输入有误"
					});
					this.getListData();
					return false;
				}
			},
			// 商品数量加减
			async countGoodsNumber(index, goodIndex, goods, flag) {
				if (flag) {
					goods.num = goods.num + (goods.moqTimes || 1);
				} else {
					let num = goods.num;
					num = num - (goods.moqTimes || 1);
					if (num <= (goods.moq? (goods.moq - 1): 0)) {
						goods.num = goods.moq || 0
						return this.myDelGoods(index, goodIndex, goods);
					}
					goods.num = num
				}
			},
			async setCartValue(index, goodIndex, goods, $event) {
				let v = $event.target.value.replace(/\D+|^0+/g, '') || 0
				let num = Number(v)
				if (num <= (goods.moq? (goods.moq - 1): 0)) {
					// 起订量校验
					goods.num = goods.moq || 0
					return this.myDelGoods(index, goodIndex, goods);
				}
				if (goods.moqTimes > 0) {
					let sub = (num - (goods.moq || 0)) % goods.moqTimes
					if (sub === 0) {
						goods.num = num
					} else {
						goods.num = num + (goods.moqTimes - sub)
					}
				} else {
					goods.num = num
				}
			},
			
			// 删除商品
			async myDelGoods(index, goodIndex, goods) {
				let _this = this;
				uni.showModal({
					title: "",
					content: "是否要删除该商品？",
					success: async function(res) {
						if (res.confirm) {
							goods.num = 0
							//删除本项目
							_this.listData[index].goodsList.splice(goodIndex, 1)
							
							uni.showToast({
							title: "商品删除成功！",
							icon: "none",
							duration: 1500
							});
						} else if (res.cancel) {
							console.log("用户点击取消");
						}
					}
				});
			},
			
			//确认订单Check
			async orderDown() {
				// if (this.Listids.length == 0) {
				//判断商品金额
				if (this.allPrice == 0) {
					uni.showToast({
						title: "请选择商品!",
						icon: "none",
						duration: 1500
					});
					return false;
				}
				
				//订单数量不能小于等于0
				for (let key in this.ListGoods) {
					if (this.ListGoods[key].num <= 0) {
					    uni.showToast({
					    title: "商品数量不能小于等于0！",
					    icon: "none",
					    duration: 1500
					    });
					    return false;
					}
				}
				let _this = this;
				let result = await checkTodayOrderCountApi({});
				let count = result.data.records[0]
				if (count > 0) {
					uni.showModal({
						title: "",
						content: "这是您今天第"+ (count + 1) +"次下单，是否继续?",
						success: async function(res) {
							if (res.confirm) {
								let ids = _this.ListGoods.map(p => p.id)
								uni.navigateTo({
									url: "/apiCart/order/main?ids=" + ids.join(',')
								});
							} else if (res.cancel) {
								let cart = getStorageCartInfo()
								cart = []
								setStorageCartInfo(cart)
								setTimeout(function() {
									uni.switchTab({
										url: "/pages/category/main"
									});
								}, 1000)
							}
						}
					});
				} else {
					let ids = this.ListGoods.map(p => p.id)
					uni.navigateTo({
						url: "/apiCart/order/main?ids=" + ids.join(',')
					});
				}
				
				
			},
			delGoods(id, index) {
				let _this = this;
				uni.showModal({
					title: "",
					content: "是否要删除该商品",
					success: async function(res) {
						if (res.confirm) {
							_this.Listids.splice(index, 1);
							// _this.getListData();
							const data = await cartDelApi({
								id: id
							});
							_this.getListData();
						} else if (res.cancel) {
							console.log("用户点击取消");
							//滑动之前先初始化样式数据
							this.initTextStyle();
						}
					}
				});
			},

			groupBy(array, f) {
				let groups = {};
				let categorys = {}
				array.forEach(function(o) {
					let group = f(o);
					groups[group] = groups[group] || [];
					groups[group].push(o);
					categorys[group] = o.categoryName;
				});

				return Object.keys(groups).map(function(group) {
					return {
						'categoryName': categorys[group],
						'categoryCode': group,
						'goodsList': groups[group]
					};
				});
			},
			getListData() {
				let cartInfo = getStorageCartInfo();
				this.Listids = []
				this.listData = []
				this.ListGoods = []
				this.SelectGoods = {}
				this.allPrice = 0
				if (cartInfo.length > 0) {
					let groups = this.groupBy(cartInfo, function(item) {
						return item.categoryCode
					})
					this.listData = groups
				}
			},
			allCheck() {
				//先清空
				if (this.allcheck) {
					this.Listids = []
					this.ListGoods = []
					for (let item in this.SelectGoods) {
						this.$set(this.SelectGoods, item, false)
					}
					this.allcheck = false
				} else {
					this.allcheck = true;
					this.listData.forEach((p, i) => {
						this.$set(this.Listids, i, true)
						p.goodsList.forEach(good => {
							this.$set(this.SelectGoods, good.id, true)
							if (this.ListGoods.findIndex(item => item.id == good.id) < 0) {
								this.ListGoods.push(good)
							}
						})
					})
				}
			},
			change(e) {},
			changeColor(index, id) {
				if (this.Listids[index]) {
					this.$set(this.Listids, index, false);
					this.listData[index].goodsList.forEach(p => {
						this.$set(this.SelectGoods, p.id, false)
						let itemIndex = this.ListGoods.findIndex(item => item.id == p.id)
						this.ListGoods.splice(itemIndex, 1)
					})
				} else {
					this.$set(this.Listids, index, id);
					this.listData[index].goodsList.forEach(p => {
						this.$set(this.SelectGoods, p.id, true)
						this.ListGoods.push(p)
					})
				}
			},
			//变更选择商品的复选框
			changeGoodsColor(index, goodIndex, good) {
				let itemIndex = this.ListGoods.findIndex(p => p.id == good.id)
				if (itemIndex > -1) {
					this.ListGoods.splice(itemIndex, 1)
					this.$set(this.SelectGoods, good.id, false)
					this.$set(this.Listids, index, false)

				} else {
					this.ListGoods.push(good)
					this.$set(this.SelectGoods, good.id, true)
					let _this = this;
					//检查该分类下的商品是不是都被选中了
					let allCheck = this.listData[index].goodsList.every(function(good) {
						if (!_this.SelectGoods[good.id]) {
							return false
						}
						return true
					})
					if (allCheck) {
						this.$set(this.Listids, index, true)
					}
				}
			},
		},
		watch: {
			listData: {
				handler(val, oldVal) {
					if (val) {
						val.forEach((p, index) => {
							if (p.goodsList.length == 0) {
								this.listData.splice(index, 1)
								this.Listids.splice(index, 1)
							}
						})
						var list = []
						val.forEach(item => {
							list = list.concat(item.goodsList)
						})
						setStorageCartInfo(list)
					}
				},
				deep: true
			}
		},
		computed: {
			isCheckedNumber() {
				let number = 0;
				for (let i = 0; i < this.Listids.length; i++) {
					if (this.Listids[i]) {
						number++;
					}
				}
				if (number == this.listData.length && number != 0) {
					this.allcheck = true;
				} else {
					this.allcheck = false;
				}

				let totalNum = 0
				let totalPrice = 0
				this.ListGoods.forEach(p => {
					totalNum += parseInt(p.num, 10);
					totalPrice += p.num * p.price
				})
				this.allPrice = totalPrice
				return totalNum;
			}
		}
	};
</script>
<style lang='scss' scoped>
	@import "./style";
</style>
